using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Collections.Generic;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Imaging;
using Sce.PlayStation.Core.Environment;
using Sce.PlayStation.HighLevel.UI;
using VitaReader;

namespace VitaReaderLibPS
{
	internal struct DownloadItem
	{
		//left side on ui
		public CheckBox		check;
		public Button 		button;
		//rigth side on ui
		public ImageBox		icon;
		public Label		status;
		public ProgressBar	progress;
		
		public bool IsMarkedForDownload()
		{
			return check != null && check.Checked;
		}
		
		public void StartDownload()
		{
			icon.Visible = false;
			status.Visible = false;
			progress.Visible = true;
			progress.Progress = 0;
		}
		
		public void FinishDownload()
		{
			icon.Visible = true;
			status.Visible = true;
			if( progress != null )
				progress.Visible = false;
		}
		
		public void UpdateDownloadProgress(float prog)
		{
			progress.Progress = prog;
		}
		
		public void UpdateState(BookState state,Download dl)
		{
			status.Text = dl.GetStateString(state);
			switch(state)
			{
			case BookState.UPDATED:
				icon.Image = dl.Scene.StateIconUpdated;
				break;
			case BookState.DIFF:
				icon.Image = dl.Scene.StateIconDifferent;
				break;
			case BookState.NOLOCAL:
				icon.Image = dl.Scene.StateIconNew;
				break;
			}
		}
		
	};
	
	internal enum BookState
	{
		UPDATED = 0,	//downloaded latest
		NOLOCAL,		//never downloaded
		DIFF,			//different between local & downloading
		//
		FAILED,			//download failed
	};
	
	internal struct DownloadableBook
	{
		public String 		Name;
		public String 		URL;
		public BookState	State;
		public long			Size;
	};
	
	//book downloading
    internal class Download : ReaderUI
    {
		Label		UILbDownloadListTitle;
		Label		UILbDownloadListCounter;
		Label		UILbCurrentURL;
		ImageBox	UIImgDownloadListBk;
		Button		UIBnBookDownload;
		Button		UIBnSelectAll;
		Button		UIBnDownloadAddress;
		ScrollPanel	UISpDownloadParent;
			ListPanel	UILpDownloadList;
		Label		UILbDownloadWait;
		
		#region languange related
		String		mStateStringUpdated;
		String		mStateStringDiff;
		String		mStateStringNew;
		internal String GetStateString(BookState state)
		{
			if( state == BookState.DIFF ) return mStateStringDiff;
			else if( state == BookState.NOLOCAL ) return mStateStringNew;
			else if( state == BookState.UPDATED ) return mStateStringUpdated;
			else return "";
		}
		#endregion
		
		private int mCurrentDownloadItem = 0;
		private List<DownloadItem> mDownloadItems;
		private int mDownloadCount;
		
		private Network mNetwork;
		private List<DownloadableBook> mDownloadableBooks;
		
		private bool mFirstShown = true;
		private bool mAllSelected = false;
		private bool mDownloading = false;
		
		#region readerUI overrides
		public override void Initialize(ReaderScene scene)
		{
			base.Initialize(scene);
			
			mNetwork = new Network();
			
			#region create
			mDownloadableBooks = new List<DownloadableBook>();
			mDownloadItems = new List<DownloadItem>();
			
			mRoot = new Panel();
			mRoot.Name = "DownloadRoot";
			mRoot.BackgroundColor = mScene.ListBackgroundColor;
			//mRoot.BackgroundStyle = DialogBackgroundStyle.Custom;
			//mRoot.CustomBackgroundColor = mScene.ListBackgroundColor;
			{
				UILbDownloadListTitle = new Label();
				UILbDownloadListTitle.Name = "UILbDownloadListTitle";
				UILbDownloadListTitle.Font = mScene.TitleFont;
				UILbDownloadListTitle.TextColor = mScene.TitleColor;
				UILbDownloadListTitle.HorizontalAlignment = HorizontalAlignment.Left;
				this.mRoot.AddChildLast(UILbDownloadListTitle);
				
				UILbDownloadListCounter = new Label();
				UILbDownloadListCounter.Name = "UILbDownloadListCounter";
				UILbDownloadListCounter.Font = mScene.FontSet.Small;
				UILbDownloadListCounter.TextColor = mScene.TitleColor;
				UILbDownloadListCounter.HorizontalAlignment = HorizontalAlignment.Right;
				this.mRoot.AddChildLast(UILbDownloadListCounter);
				
				UILbCurrentURL = new Label();
				UILbCurrentURL.Name = "CurrentURL";
				UILbCurrentURL.Font = mScene.FontSet.Middle;
				UILbCurrentURL.TextColor = mScene.TitleColor;
				UILbCurrentURL.Text = mScene.Reader.DownloadURL;
				this.mRoot.AddChildLast(UILbCurrentURL);
				
				UIImgDownloadListBk = new ImageBox();
				UIImgDownloadListBk.Name = "UIImgDownloadListBk";
	            UIImgDownloadListBk.Image = mScene.ListBackgroundImage;
	            UIImgDownloadListBk.ImageScaleType = ImageScaleType.Stretch;
				UIImgDownloadListBk.Visible = true;
				this.mRoot.AddChildFirst(UIImgDownloadListBk);
				
				UIBnBookDownload = new Button();
	            UIBnBookDownload.Name = "UIBnBookDownload";
	            UIBnBookDownload.TextColor = mScene.ButtonTextColor;
	            UIBnBookDownload.TextFont = mScene.ButtonTextFont;
	            UIBnBookDownload.Style = ButtonStyle.Custom;
	            UIBnBookDownload.CustomImage = mScene.ButtonImage;
				UIBnBookDownload.Visible = true;
				this.mRoot.AddChildLast(UIBnBookDownload);
				
				UIBnDownloadAddress = new Button();
				UIBnDownloadAddress.Name = "UIBnDownloadAddress";
				UIBnDownloadAddress.TextColor = mScene.ButtonTextColor;
				UIBnDownloadAddress.TextFont = mScene.ButtonTextFont;
				UIBnDownloadAddress.Style = ButtonStyle.Custom;
				UIBnDownloadAddress.CustomImage = mScene.ButtonImage;
				UIBnDownloadAddress.Visible = true;
				UIBnDownloadAddress.ButtonAction += HandleDownloadAddress;
				this.mRoot.AddChildLast(UIBnDownloadAddress);
				
				UIBnSelectAll = new Button();
	            UIBnSelectAll.Name = "UIBnSelectAll";
	            UIBnSelectAll.TextColor = mScene.ButtonTextColor;
	            UIBnSelectAll.TextFont = mScene.ButtonTextFont;
	            UIBnSelectAll.Style = ButtonStyle.Custom;
	            UIBnSelectAll.CustomImage = mScene.ButtonImage;
				UIBnSelectAll.Visible = true;
				this.mRoot.AddChildLast(UIBnSelectAll);
				
				
				UISpDownloadParent = new ScrollPanel();
				UISpDownloadParent.Name = "UISpDownloadParent";
				UISpDownloadParent.PanelColor = new UIColor(0,0,0,0);
				UISpDownloadParent.ScrollBarVisibility = ScrollBarVisibility.Invisible;
				UISpDownloadParent.VerticalScroll = true;
				UISpDownloadParent.HorizontalScroll = false;
				UISpDownloadParent.Visible = true;
				this.mRoot.AddChildLast(UISpDownloadParent);
				
		            UILpDownloadList = new ListPanel();
		            UILpDownloadList.Name = "UILpDownloadList";
		            UILpDownloadList.ScrollBarVisibility = ScrollBarVisibility.Invisible;
					UILpDownloadList.Visible = true;
					this.UISpDownloadParent.AddChildFirst(UILpDownloadList);
				
				UILbDownloadWait = new Label();
				UILbDownloadWait.Name = "UILbDownloadListTitle";
				UILbDownloadWait.Font = mScene.TitleFont;
				UILbDownloadWait.TextColor = mScene.TitleColor;
				UILbDownloadWait.BackgroundColor = new UIColor(1,1,1,0.8f);//mScene.DialogBackgroundColor;
				UILbDownloadWait.HorizontalAlignment = HorizontalAlignment.Center;
				UILbDownloadWait.VerticalAlignment = VerticalAlignment.Middle;
				this.mRoot.AddChildLast(UILbDownloadWait);
			}
			//this.RootWidget.AddChildLast(mRoot);
			#endregion
			
			#region init
			DragGestureDetector drag = new DragGestureDetector();
			drag.MaxDistance = 10;
			drag.DragDetected += HandleDownloadListDrag;
			UISpDownloadParent.AddGestureDetector(drag);
			
			mRoot.KeyEventReceived += HandleDownloadListKey;
			UIBnBookDownload.ButtonAction += HandleDownloadBook;
			UIBnSelectAll.ButtonAction += HandleSelectAll;
			
			UIBnBookDownload.Focusable = false;
			UIBnSelectAll.Focusable = false;
			
			UILpDownloadList.FocusStyle = FocusStyle.None;
			UILpDownloadList.Focusable = false;
			
			UISpDownloadParent.FocusStyle = FocusStyle.None;
			UISpDownloadParent.Focusable = false;
			
			//UILbBookDownloadInfo.Font = (mView as PSView).FontSet.Middle;
			
			//FillDownloadList();
			//mCurrentDownloadItem = 0;
			#endregion
		}
		
		public override void OnShown()
		{
			RefreshDownloadList();
		}
		
		public override void OnHidden()
		{
			if( UILpDownloadList.Sections != null )
			{
				UILpDownloadList.Sections.Clear();
				UILpDownloadList.Sections = null;
			}
		}
		
		public override void UpdateLayout(LayoutOrientation orientation)
		{
			switch (orientation)
            {
            case LayoutOrientation.Vertical:
				break;
			default:
				float btnPadding = mScene.View.ButtonPadding;
				float btnWidth = mScene.View.ButtonWidth;
				float btnHeight = mScene.View.ButtonHeight;
				float Gap = 45.0f;
				
				//downloads
				mRoot.SetPosition(0,0);
				mRoot.SetSize(mScene.View.Width,mScene.View.Height);
				mRoot.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
				//mRoot.Visible = false;
				{
					float borderPadding = 6.0f;
					float titleHeight = UILbDownloadListTitle.Font.GetFont().Metrics.Height;
					UILbDownloadListTitle.SetPosition(borderPadding,borderPadding);
					UILbDownloadListTitle.SetSize(mScene.View.Width/2-Gap-borderPadding, titleHeight );
					
					UILbDownloadListCounter.SetPosition(borderPadding,borderPadding);
					UILbDownloadListCounter.SetSize(mScene.View.Width/2-Gap-borderPadding, titleHeight );
					
					UILbCurrentURL.SetPosition(mScene.View.Width/2+Gap,borderPadding);
					UILbCurrentURL.SetSize(mScene.View.Width/2-Gap, titleHeight);
					
					UIBnBookDownload.SetPosition( mScene.View.Width-btnWidth-btnPadding, mScene.View.Height-btnHeight-btnPadding );
					UIBnBookDownload.SetSize(btnWidth, btnHeight);
					
					UIBnDownloadAddress.SetPosition( mScene.View.Width-btnWidth*2-btnPadding*2, mScene.View.Height-btnHeight-btnPadding);
					UIBnDownloadAddress.SetSize(btnWidth, btnHeight);
					
					UIBnSelectAll.SetPosition( mScene.View.Width-btnWidth*3-btnPadding*3, mScene.View.Height-btnHeight-btnPadding );
					UIBnSelectAll.SetSize(btnWidth, btnHeight);
					
					UIImgDownloadListBk.SetPosition(0,0);
					UIImgDownloadListBk.SetSize(mScene.View.Width,UIBnBookDownload.Y-btnPadding);
					UIImgDownloadListBk.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
					
					//
					float height = UIBnBookDownload.Y - btnPadding - titleHeight - borderPadding*2;
					UISpDownloadParent.SetPosition(borderPadding,titleHeight+borderPadding);
					UISpDownloadParent.SetSize(mScene.View.Width-btnPadding*2,height);
					UISpDownloadParent.PanelWidth = UISpDownloadParent.Width;
					UISpDownloadParent.PanelHeight = height;
					UISpDownloadParent.Visible = true;
					
						UILpDownloadList.SetPosition(0, 0);
		                UILpDownloadList.SetSize(UISpDownloadParent.Width, height);
		                UILpDownloadList.Anchors = Anchors.Top | Anchors.Height | Anchors.Left | Anchors.Width;
		                UILpDownloadList.Visible = true;
					
					UILbDownloadWait.SetPosition(0,0);
					UILbDownloadWait.SetSize(mScene.View.Width,mScene.View.Height);
					if( mDownloading )
						UILbDownloadWait.Visible = true;
					else
						UILbDownloadWait.Visible = false;
				}
				break;
			}
		}
		
		public override void UpdateLanguage(StreamReader reader)
		{
			String s = reader.ReadLine();
			String[] items = s.Split(',');
			int count = 0;
			if( count < items.Length )
				UILbDownloadListTitle.Text = items[count++];
			if( count < items.Length )
			{
				if( Sce.PlayStation.Core.Environment.SystemParameters.GamePadButtonMeaning == GamePadButtonMeaning.CircleIsEnter )
					UIBnBookDownload.Text = "X " + items[count++];
				else
					UIBnBookDownload.Text = "○ " + items[count++];
			}
			if( count < items.Length )
				UIBnDownloadAddress.Text = items[count++];
			if( count < items.Length )
				UIBnSelectAll.Text = items[count++];
			
			
			if( count < items.Length )
				mStateStringUpdated = items[count++];
			if( count < items.Length )
				mStateStringNew = items[count++];
			if( count < items.Length )
				mStateStringDiff = items[count++];
			if( count < items.Length )
				UILbDownloadWait.Text = items[count++];
		}
		
		public override void Update()
		{
			if( mDownloading )
			{
				int index = mNetwork.UpdateDownloadBooks(mScene.Data.BookPath,ref mDownloadableBooks,ref mDownloadItems );
				if( index >= mDownloadableBooks.Count )
				{
					UILbDownloadWait.Visible = false;
					mDownloading = false;

					/*
					//update states
					UpdateBookState();

					for(int i = 0; i < mDownloadItems.Count; ++i)
					{
						Console.WriteLine(i);
						mDownloadItems[i].FinishDownload();
						mDownloadItems[i].UpdateState(mDownloadableBooks[i].State,this);
					}
					*/
					this.RefreshDownloadList();
				}
				else
				{
					ListPanelItem item = mDownloadItems[index].progress.Parent as ListPanelItem;
					this.EnsureListItemVisible(item,UISpDownloadParent);
				}
			}
		}
		#endregion
		
		private void HandleDownloadListKey(object sender, KeyEventArgs e)
		{
			if( this.Showing || this.Hiding || this.mDownloading )
				return;

			if( e.KeyEventType != KeyEventType.Up )
				return;
			
			switch(e.KeyType)
			{
			case KeyType.Triangle:
				SelectAll();
				break;
			case KeyType.Square:
				InputDownloadAddress();
				break;
			case KeyType.Enter:
				if( mCurrentDownloadItem < mDownloadItems.Count && mCurrentDownloadItem >= 0 )
				{
					CheckBox check = mDownloadItems[mCurrentDownloadItem].check;
					if( check != null )
						check.Checked = !check.Checked;
				}
				break;
			case KeyType.Back:
				StartDownloadProgress();
				break;
			case KeyType.Up:
			case KeyType.Left:
				if( mDownloadItems.Count == 0)
					mCurrentDownloadItem = 0;
				else if( --mCurrentDownloadItem < 0 )
					mCurrentDownloadItem = mDownloadItems.Count-1;
				UpdateSelectedDownloadItem();
				break;
				
			case KeyType.Down:
			case KeyType.Right:
				if(mDownloadItems.Count == 0)
					mCurrentDownloadItem = 0;
				else if( ++mCurrentDownloadItem >= mDownloadItems.Count )
					mCurrentDownloadItem = 0;
				UpdateSelectedDownloadItem();
				break;
			case KeyType.R:
				//R/L swtich between local books / downloading list
				mScene.ShowUI(UIType.BOOKS,UISwitch.LEFT);
				break;
			}//switch
		}
		
		private void HandleDownloadListDrag(object sender, DragEventArgs e)
		{
			if( this.Showing || this.Hiding || mDownloading)
				return;

			DragType drag = mScene.Control.DetectDrag(e.Distance.X,e.Distance.Y);
			
			//horizontal drag, same as button R
			if( drag == DragType.RIGHT )
				mScene.ShowUI(UIType.BOOKS,UISwitch.LEFT);
		}
		
		private void HandleSelectAll(object sender, TouchEventArgs e)
		{
			SelectAll();
		}

		private void HandleDownloadBook(object sender, TouchEventArgs e)
		{
			StartDownloadProgress();
		}
		
		private void HandleDownloadAddress(object sender, TouchEventArgs e)
		{
			InputDownloadAddress();
		}
		
		private void SelectAll()
		{
			if( mDownloadItems.Count == 0
			   || mDownloadableBooks.Count == 0
			   || mDownloadItems.Count != mDownloadableBooks.Count
			   )
				return;
			
			mAllSelected = !mAllSelected;
			for(int i = 0; i < mDownloadItems.Count; ++i)
			{
				DownloadItem item = mDownloadItems[i];
				if( item.check != null )
					item.check.Checked = mAllSelected;
			}
		}
		
		private void RefreshDownloadList()
		{			
			UISpDownloadParent.RemoveChild( UILpDownloadList );
			float width = UILpDownloadList.Width;
			float x = UILpDownloadList.X;
			float y = UILpDownloadList.Y;
			UILpDownloadList.Dispose();
			UILpDownloadList = new ListPanel();
			UILpDownloadList.Width = width;
			UILpDownloadList.SetPosition(x,y);
			UILpDownloadList.Visible = true;
			UISpDownloadParent.AddChildLast(UILpDownloadList);
			this.UpdateLayout(mScene.Layout);
			
			FillDownloadList();
			UpdateSelectedDownloadItem();
			UpdateBookState();
		}
		
		private void FillDownloadList()
		{
			mDownloadItems.Clear();
			mDownloadCount = 0;
			
			//sync network to get file list
			if( mScene.Reader.DownloadURL == "" )
			{
				//request download address
				mFirstShown = false;
				InputDownloadAddress();
				return;
			}
			
			if( mFirstShown )
			{
				mNetwork.TestConnection( mScene.Reader.DownloadURL );
				mDownloadableBooks.Clear();
				mNetwork.GetDownloadBookList( mScene.Reader.DownloadURL, ref mDownloadableBooks );
				UpdateBookState();
				mFirstShown = false;
			}
			
			//try sync list from server
			//Console.WriteLine("sync");
			
			int DownloadBookCount = mDownloadableBooks.Count;
			//if( DownloadBookCount == 0 )
			//	return;
			
			if( UISpDownloadParent.Height <= LIST_BUTTON_HEIGHT*DownloadBookCount)
				UISpDownloadParent.PanelHeight = LIST_BUTTON_HEIGHT*DownloadBookCount;
			UISpDownloadParent.PanelX = 0;
			UISpDownloadParent.PanelY = 0;

			UILpDownloadList.SetListItemCreator(DownloadItemCreator);
			ListSectionCollection section = new ListSectionCollection();
			

			section.Add( new ListSection("Download Book List", DownloadBookCount) );
			UILpDownloadList.Sections = section;//.Add( new ListSection("Book List", BookCount) );

			UILpDownloadList.ShowSection = false;			
			UILpDownloadList.ShowItemBorder = false;
		}
		
		private ListPanelItem DownloadItemCreator()
		{
			//force set height, or it will be cliped
			UILpDownloadList.Height = UISpDownloadParent.PanelHeight;
			
			const float Gap = 40.0f;
			const float borderPadding = 6.0f;
			float ButtonWidth = UILpDownloadList.Width/2-Gap;

						
			ListPanelItem item = new ListPanelItem();
			item.SetSize(UILpDownloadList.Width, LIST_BUTTON_HEIGHT);
			item.Focusable = false;
			item.Visible = true;
			
			Panel left = new Panel();
			left.SetPosition(0, 0);
            left.SetSize(ButtonWidth, LIST_BUTTON_HEIGHT);
            left.Anchors = Anchors.Top | Anchors.Bottom | Anchors.Left | Anchors.Right;
            left.Visible = true;
			item.AddChildLast(left);

			
			DownloadItem downloaditem;
			
			//check local books, if exists, do not create the check box and progress bar
			if( mDownloadableBooks[mDownloadCount].State != BookState.UPDATED )
			{
				CheckBox box = new CheckBox();
				box.SetPosition(0,0);
				box.SetSize(LIST_BUTTON_HEIGHT,LIST_BUTTON_HEIGHT);				
				box.Checked = false;
				box.Name = "DownloadCheckItem." + mDownloadCount;
				box.Style = CheckBoxStyle.Custom;
				box.CustomCheckBoxImage = mScene.mCheckImage;
				box.CheckedChanged += HandleDownloadItem;
				left.AddChildLast(box);
				downloaditem.check = box;
				
				ProgressBar progress = new ProgressBar();
				progress.SetSize(mScene.View.Width/2-Gap-borderPadding,LIST_BUTTON_HEIGHT);//height is ignored
				progress.Width = progress.Width - borderPadding;
				progress.SetPosition( mScene.View.Width/2+Gap, (LIST_BUTTON_HEIGHT-progress.Height)/2 );
				progress.Visible = false;
				item.AddChildLast(progress);
				downloaditem.progress = progress;
			}
			else
			{
				downloaditem.check = null;
				downloaditem.progress = null;
			}
			
			Button button = new Button();
			button.Name = "DownloadItem." + mDownloadCount;
			button.Text = mDownloadableBooks[mDownloadCount].Name;
			button.SetPosition(LIST_BUTTON_HEIGHT, 0);
            button.SetSize(ButtonWidth-LIST_BUTTON_HEIGHT, LIST_BUTTON_HEIGHT);
            button.Anchors = Anchors.Top | Anchors.Bottom | Anchors.Left | Anchors.Right;
            button.Visible = true;
			
			button.Style = ButtonStyle.Custom;
			button.HorizontalAlignment = HorizontalAlignment.Left;
            button.TextColor = mScene.ListItemTextColor;
            button.TextFont = mScene.ListItemTextFont;
            button.CustomImage = null;//mScene.ListImage;
			button.ButtonAction += HandleDownloadItem;
			button.Focusable = false;
			left.AddChildFirst(button);
			downloaditem.button = button;
			
			float iconSize = LIST_BUTTON_HEIGHT-10;
			float iconLeft = mScene.View.Width/2+Gap+(LIST_BUTTON_HEIGHT-iconSize)/2;
			float iconTop = (LIST_BUTTON_HEIGHT-iconSize)/2;
			ImageBox icon = new ImageBox();
			icon.SetPosition(iconLeft, iconTop);
			icon.SetSize(iconSize,iconSize);
			icon.ImageScaleType = ImageScaleType.Stretch;
			item.AddChildLast(icon);
			downloaditem.icon = icon;
			
			Label status = new Label();
			status.SetPosition(iconLeft+iconSize,0);
			status.SetSize(mScene.View.Width/2-Gap-iconSize-borderPadding,LIST_BUTTON_HEIGHT);
			status.TextColor = mScene.TitleColor;
			status.Font = mScene.FontSet.Small;
			item.AddChildLast(status);
			downloaditem.status = status;
			
			//update icon & status text
			downloaditem.UpdateState( mDownloadableBooks[mDownloadCount].State, this);
			
			mDownloadCount++;
			mDownloadItems.Add ( downloaditem );
			
			UpdateSelectedDownloadItem();
			return item;
		}
		
		private void UpdateSelectedDownloadItem()
		{
			//check download data info
			if( mDownloadItems == null || mCurrentDownloadItem >= mDownloadItems.Count )
			{
				UILbDownloadListCounter.Text = "0/0";
				return;
			}
			UILbDownloadListCounter.Text = Convert.ToString(mCurrentDownloadItem+1)+'/'+Convert.ToString(mDownloadCount);
			
			for(int i = 0; i < mDownloadItems.Count; ++i)
			{
				Panel leftPanel = mDownloadItems[i].button.Parent as Panel;
				
				if( i == mCurrentDownloadItem )
				{
					//mDownloadItems[i].button.CustomImage = mScene.HilightListImage;
					leftPanel.BackgroundColor = mScene.ListItemHilightColor;
					EnsureListItemVisible(leftPanel.Parent as ListPanelItem,UISpDownloadParent);
				}
				else
				{
					//mDownloadItems[i].button.CustomImage = mScene.ListImage;
					leftPanel.BackgroundColor = mScene.ListItemColor;
				}
			}
		}
		
		private void HandleDownloadItem(object sender, TouchEventArgs e)
		{
			if( mDownloadItems == null )
				return;
			
			Widget w = sender as Widget;
			String[] s = w.Name.Split('.');
			if( s.Length < 2 )
				return;
			int index = Convert.ToInt32(s[1]);
			if( index >= mDownloadItems.Count )
				return;
			
			if(mDownloadItems[index].check != null && sender != mDownloadItems[index].check)			
				mDownloadItems[index].check.Checked = !mDownloadItems[index].check.Checked;
			
			mCurrentDownloadItem = index;
			UpdateSelectedDownloadItem();
		}
		
		private void StartDownloadProgress()
		{
			if( mDownloadableBooks.Count == 0 || mDownloadableBooks.Count != mDownloadItems.Count )
				return;
			
			//downloda in sync mode
			mNetwork.StartDownload();
			
			UpdateBookState();
			mDownloading = true;
			UILbDownloadWait.Visible = true;
		}
		
		private void InputDownloadAddress()
		{
			mDownloadableBooks.Clear();
			
			InputBox box = new InputBox( mScene.Language.TitleInput, mScene.Language.MsgInputServerAddress, mScene, HandleInputBox);
			box.SetDefaultInput( mScene.Reader.DownloadURL );
			box.Show();
		}
		
		private void HandleInputBox(object target)
		{
			String text = (target as EditableText).Text;
			
			if( text == "" )
			{
				InputDownloadAddress();
				return;
			}
			
			//keep the text
			UILbCurrentURL.Text = text;
			mScene.Reader.DownloadURL = text;

			
			if( mNetwork.TestConnection(text) )	//test server connection
			{
				MessageBox box = new MessageBox(
					mScene.Language.TitleSuccess,
					mScene.Language.MsgGoodConnection,
					mScene,
					MessageDialogStyle.Ok,
					HandleAddressValid,null);
				
				box.Show();
			}
			else
			{
				MessageBox box = new MessageBox(
					mScene.Language.TitleError,
					mScene.Language.MsgBadConnection,
					mScene);
				box.Show();
			}
		}
		
		private void HandleAddressValid(object target)
		{
			//connection good, try sync list again:
			//Console.WriteLine("FUCK!");
			mNetwork.GetDownloadBookList( mScene.Reader.DownloadURL, ref mDownloadableBooks );
			UpdateBookState();
			RefreshDownloadList();
		}
		
		private void UpdateBookState()
		{
			mScene.Data.RefreshBookInfo();
			for(int i = 0; i < mDownloadableBooks.Count; ++i)
			{
				DownloadableBook book = mDownloadableBooks[i];
				//TODO: compare to local books
				BookInfo info;
				info.BookMarks = null;
				info.FileName = null;
				info.FullPath = null;
				info.LastPos = 0;
				info.Size = 0;
				info.Title = null;
				if( mScene.Data.GetBookInfo( book.Name, out info ) )
				{
					#region compare file size
					/*
					if( info.Size == book.Size )
						book.State = BookState.UPDATED;
					else
						book.State = BookState.DIFF;
					*/
					#endregion
					//Console.WriteLine(info.FullPath);
					book.State = BookState.UPDATED;
				}
				else
					book.State = BookState.NOLOCAL;
				
				mDownloadableBooks[i] = book;
			}
		}
		
	}//class
}